package com.bdqn.controller;

import com.alibaba.fastjson.JSON;
import com.bdqn.pojo.SysRole;
import com.bdqn.pojo.SysUser;
import com.bdqn.service.SysRoleService;
import com.bdqn.service.SysRoleServiceImpl;
import com.bdqn.service.SysUserService;
import com.bdqn.service.SysUserServiceImpl;
import com.bdqn.util.Page;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * SysUserController
 *
 * @author LILIBO
 * @since 2022-09-08
 */
@WebServlet("/user")
@MultipartConfig
public class SysUserController extends HttpServlet {
    /**
     * 接收初始化参数
     */
    private String uploadPath;

    /**
     * Servlet初始化（执行一次）
     *
     * @param config Servlet参数
     * @throws ServletException
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);

        // 获取全局初始化参数
        uploadPath = this.getServletContext().getInitParameter("uploadPath");
        System.out.println("全局初始化参数: uploadPath=" + uploadPath);
    }

    // 引入SysUserService
    private SysUserService sysUserService = new SysUserServiceImpl();

    // 引入SysRoleService
    private SysRoleService sysRoleService = new SysRoleServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置编码方式
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        HttpSession session=request.getSession();
        // 控制参数
        String opr = request.getParameter("opr");
        switch (opr) {
            case "login": // 用户登录
                login(request, response);
                break;
            case "logout": // 退出系统
                logout(request, response);
                break;
            case "list": // 分页查询用户信息
                list(request, response);
                break;
            case "del":
                delete(request,response);
                break;
            case "toadd":
                toadd(request,response);
                break;
            case "doadd":
                add(request,response);
                break;
            case "account":
                account(request,response);
                break;
            case "toupdate":
                toupdate(request,response);
                break;
            case "doupdate":
                doupdate(request,response);
                break;
            case "toview":
                toview(request,response);
                break;
            case "toUpdatePwd":
                toUpdatePwd(request,response);
                break;
            case "checkOldPwd":
                checkOldPwd(request,response);
                break;
            case "savePassword":
                savePassword(request,response);
                break;
            default:
                break;
        }
    }

    private void savePassword(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String newPassword=request.getParameter("newPassword");
        String uid=request.getParameter("id");
        int id = 0;
        if (uid!=null){
            id= Integer.parseInt(uid);
        }
        int row=sysUserService.updatePwd(newPassword,id);
        if (row>0){
            response.getWriter().print("<script>alert('修改成功');window.location='user?opr=list';</script>");
        }
        response.getWriter().flush();
        response.getWriter().close();
    }

    private void checkOldPwd(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SysUser sysUser=(SysUser) request.getSession().getAttribute("USER_SESSION");
        String oldPassword=request.getParameter("oldPassword");
        int row=sysUserService.getByCountPwd(oldPassword);
        String result="false";
        if (row>0){
            result="true";
        }else if (oldPassword==""||oldPassword==null){
            result="error";
        }else if (sysUser==null){
            result="sessionerror";
        }else{
            result="false";
        }
        Map<String,String>map=new HashMap<>();
        map.put("result",result);
        String resultJson= JSON.toJSONString(map);
        response.getWriter().print(resultJson);
        response.getWriter().flush();
        response.getWriter().close();
    }


    private void toUpdatePwd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        SysUser sysUser=(SysUser) request.getSession().getAttribute("USER_SESSION");
        request.setAttribute("id",sysUser.getId());
        request.getRequestDispatcher("WEB-INF/jsp/sysUser/updatePassword.jsp").forward(request,response);
    }

    private void toview(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id= Integer.parseInt(request.getParameter("id"));
        SysUser sysUser=sysUserService.getView(id);
        request.setAttribute("sysUser",sysUser);
        request.getRequestDispatcher("WEB-INF/jsp/sysUser/view.jsp").forward(request,response);
    }

    private void doupdate(HttpServletRequest request, HttpServletResponse response) throws IOException {
        SysUser sysUser=new SysUser();
        int id= Integer.parseInt(request.getParameter("id"));
        sysUser.setId( id);
        String account=request.getParameter("account");
        sysUser.setAccount(account);
        String realName=request.getParameter("realName");
        sysUser.setRealName(realName);
        int sex= Integer.parseInt(request.getParameter("sex"));
        sysUser.setSex((long) sex);
        String birthday=request.getParameter("birthday");
        sysUser.setBirthday(birthday);
        String phone=request.getParameter("phone");
        sysUser.setPhone(phone);
        String address=request.getParameter("address");
        sysUser.setAddress(address);
        int roleId= Integer.parseInt(request.getParameter("roleId"));
        sysUser.setRoleId((long) roleId);
        int row=sysUserService.setUpdate(sysUser);
        if (row>0){
            response.getWriter().print("<script>alert('修改成功');window.location='user?opr=list';</script>");
        }
    }

    private void toupdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id= Integer.parseInt(request.getParameter("id"));
        SysUser sysUser=sysUserService.getUpdate(id);
        request.setAttribute("sysUser",sysUser);
        request.getRequestDispatcher("WEB-INF/jsp/sysUser/update.jsp").forward(request,response);
    }

    /**
     * 去新增页面
     */
    private void toadd(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        List<SysRole> roleList=sysRoleService.getByRoleName();
        request.setAttribute("roleList",roleList);
        request.getRequestDispatcher("WEB-INF/jsp/sysUser/add.jsp").forward(request,response);
    }

    /**
     * 新增用户
     * @param request
     * @param response
     * @throws IOException
     * @throws ServletException
     */
    private void add(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        SysUser sysUser=new SysUser();
        String account=request.getParameter("account");
        sysUser.setAccount(account);
        String realName=request.getParameter("realName");
        sysUser.setRealName(realName);
        String password=request.getParameter("password");
        sysUser.setPassword(password);
//        String rpassword=request.getParameter("rpassword");

        int sex= Integer.parseInt(request.getParameter("sex"));
        sysUser.setSex((long) sex);
        String birthday=request.getParameter("birthday");
        sysUser.setBirthday(birthday);
        String phone=request.getParameter("phone");
        sysUser.setPhone(phone);
        String address=request.getParameter("address");
        sysUser.setAddress(address);
        int roleId= Integer.parseInt(request.getParameter("roleId"));
        sysUser.setRoleId((long) roleId);
        Part idPic = request.getPart("idPic");
        String fileName = extractFileName(idPic);
        sysUser.setIdPicPath(fileName);
        idPic.write(uploadPath + File.separator + fileName);

        Part workPic = request.getPart("workPic");
        String file = extractFileName(workPic);
        sysUser.setWorkPicPath(file);
        workPic.write(uploadPath + File.separator + file);

        System.out.println(" 头像上传成功！-> " + fileName);

        int row=sysUserService.addUser(sysUser);
        if (row>0){
            request.getRequestDispatcher("user?opr=list").forward(request,response);
        }
        
    }

    /**
     * ajax异位查询用户名称
     * @param request
     * @param response
     * @throws IOException
     */
    private void account(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String account=request.getParameter("account");
        int exist=sysUserService.getByCount(account);
        Map<String,Integer>map=new HashMap<>();
        map.put("exist",exist);
        String resultJson= JSON.toJSONString(map);
        response.getWriter().print(resultJson);
        response.getWriter().flush();
        response.getWriter().close();


    }

    /**
     * 删除角色
     * @param request
     * @param response
     * @throws IOException
     */
    private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int id= Integer.parseInt(request.getParameter("id"));
        SysUser sysUser=sysUserService.getId(id);
        String delResult="notexist";
        if (sysUser!=null){
            int del=sysUserService.deleteUser(id);
            delResult=del==1?"true":"false";
        }
        Map<String,String>map=new HashMap<>();
        map.put("delResult",delResult);
        String resultJson= JSON.toJSONString(map);
        response.getWriter().print(resultJson);
        response.getWriter().flush();
        response.getWriter().close();
    }

    /**
     * 用户登录
     */
    private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String account = request.getParameter("account");
        String password = request.getParameter("password");
        SysUser loginUser = sysUserService.login(account, password);
        // 如果登录失败，返回登录页，并提示错误
        if (loginUser == null) {
            request.setAttribute("error", "账号或密码错误");
            request.getRequestDispatcher("WEB-INF/jsp/login.jsp").forward(request, response);
            return;
        }
        request.getSession().setAttribute("USER_SESSION", loginUser);
        request.getRequestDispatcher("WEB-INF/jsp/frame.jsp").forward(request, response);
    }

    /**
     * 退出系统
     */
    private void logout(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        // 清除Session中的数据
        request.getSession().removeAttribute("USER_SESSION");
        // 销毁Session
        request.getSession().invalidate();
        request.getRequestDispatcher("WEB-INF/jsp/login.jsp").forward(request, response);
    }

    /**
     * 分页查询用户信息
     */
    private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取页面查询参数
        String queryRealName = request.getParameter("queryRealName");
        String queryRoleId = request.getParameter("queryRoleId");
        String pageIndex = request.getParameter("pageIndex");

        // 处理角色ID参数
        int roleId = (queryRoleId == null || "".equals(queryRoleId)) ? 0 : Integer.parseInt(queryRoleId);

        // 分页参数（默认查询第1页）
        int pageNo = (pageIndex == null || "".equals(pageIndex)) ? 1 : Integer.parseInt(pageIndex);

        // 获取所有角色信息填充下拉列表
        List<SysRole> roleList = sysRoleService.getAll();

        // 构建分页对象
        Page<SysUser> page = new Page<>();
        // 查询总数据量
        int count = sysUserService.count(queryRealName, roleId);
        page.setTotalCount(count); // 总数据量
        // 先设置总数据量再设置页码
        page.setCurrPageNo(pageNo);
        // 查询分页数据
        List<SysUser> pageList = sysUserService.queryPageByRealNameAndRoleId(queryRealName, roleId, page);
        page.setList(pageList);

        // 数据回显
        request.setAttribute("queryRealName", queryRealName);
        request.setAttribute("queryRoleId", queryRoleId);
        // 填充角色下拉列表
        request.setAttribute("roleList", roleList);
        // 分页数据
        request.setAttribute("page", page);

        // 跳转到列表页面
        request.getRequestDispatcher("WEB-INF/jsp/sysUser/list.jsp").forward(request, response);
    }
    /**
     * 获取上传的文件名
     *
     * @param part
     * @return
     */
    private String extractFileName(Part part) {
        String fileName = "";
        String contentDisp = part.getHeader("content-disposition");
        String[] items = contentDisp.split(";");
        for (String s : items) {
            if(s.startsWith("filename")) {
                fileName =  s.substring(s.indexOf("=") + 2, s.length() - 1);
                break;
            }
        }
        return fileName;
    }

}
